package com.fly.swt.launch;

import java.util.concurrent.TimeUnit;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class LoadWindow
{
    
    /**
     * Launch the application.
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        try
        {
            LoadWindow window = new LoadWindow();
            window.open();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * Open the window.
     */
    public void open()
    {
        Display display = Display.getDefault();
        Shell topShell = new WorkShell(display, SWT.SHELL_TRIM);
        
        // 设置默认居中后隐藏
        Rectangle screeRec = display.getBounds();
        Rectangle shellRec = topShell.getBounds();
        if (shellRec.height > screeRec.height)
        {
            shellRec.height = screeRec.height;
        }
        if (shellRec.width > screeRec.width)
        {
            shellRec.width = screeRec.width;
        }
        topShell.setLocation((screeRec.width - shellRec.width) / 2, (screeRec.height - shellRec.height) / 2);
        topShell.setAlpha(0);
        topShell.setVisible(false);
        topShell.setText("SWT Application");
        topShell.open();
        topShell.layout();
        
        // 设置图片默认居中
        Shell imageShell = new ImageShell(topShell);
        Image image = new Image(display, getClass().getResourceAsStream("/img/start.jpg"));
        imageShell.setSize(image.getBounds().width, image.getBounds().height);
        Canvas canvas = new Canvas(imageShell, SWT.NONE);
        canvas.setBackgroundImage(image);
        canvas.setBounds(0, 0, image.getBounds().width, image.getBounds().height);
        screeRec = display.getBounds();
        shellRec = imageShell.getBounds();
        if (shellRec.height > screeRec.height)
        {
            shellRec.height = screeRec.height;
        }
        if (shellRec.width > screeRec.width)
        {
            shellRec.width = screeRec.width;
        }
        imageShell.setLocation((screeRec.width - shellRec.width) / 2, (screeRec.height - shellRec.height) / 2);
        imageShell.open();
        
        try
        {
            // 等待
            TimeUnit.SECONDS.sleep(5);
        }
        catch (InterruptedException e)
        {
        }
        imageShell.dispose();
        
        // 显示之前隐藏的shell
        topShell.setAlpha(255);
        topShell.setVisible(true);
        while (!topShell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
    }
}
